package com.wh.wisdomsite.xbox.server.controller.workflow;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseApplyIn;
import com.wh.wisdomsite.xbox.pojo.workflow.PurchaseIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.PurchaseApply;
import com.wh.wisdomsite.xbox.st.entity.PurchaseDetail;
import com.wh.wisdomsite.xbox.st.entity.PurchaseFile;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseFileService;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IEmployeeService;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 采购流程业务单controller
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.wo
 * @date 2018年09月21日 9:25
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/purchase")
public class PurchaseController {

    private static final Log logger = LogFactory.getLog(PurchaseController.class);

    @Resource
    private HistoryService historyService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;

    @Autowired
    private IPurchaseDetailService iPurchaseDetailService;

    @Autowired
    private IPurchaseFileService iPurchaseFileService;

    @Autowired
    private ICommonFileService iCommonFileService;

    @Autowired
    private IPurchaseApplyService purchaseApplyService;

    @Autowired
    private IEmployeeService iEmployeeService;


    /**
     * 跳转至-》已录入事项
     * @return
     */

    @RequestMapping(value = "/myInput.do", method = RequestMethod.GET)
    public String myInputPage() {
        return "workflow/purchase/myInput";
    }


    /**
     * 跳转至-》审核中事项
     * @return
     */
    @RequestMapping(value = "/myAudit.do", method = RequestMethod.GET)
    public String myAudit() {
        return "workflow/purchase/myAudit";
    }


    /**
     * 跳转至-》已通过事项
     * @return
     */

    @RequestMapping(value = "/myFinish.do", method = RequestMethod.GET)
    public String myFinish() {
        return "workflow/purchase/myFinish";
    }


    /**
     * 跳转至-》已驳回事项
     * @return
     */
    @RequestMapping(value = "/myReturn.do", method = RequestMethod.GET)
    public String myReturn() {
        return "workflow/purchase/myReturn";
    }



    /**
     * 已录入事项
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:workflow_purchase_myInputPage")
    @RequestMapping(value = "/myInputList.do", method = RequestMethod.POST)
    public void myInputList(HttpServletResponse response, PurchaseApplyIn in) {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        try {
            logger.info("已录入事项->>开始");
            User user = UserUtils.getCurrentUser();
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            PurchaseApply purchaseApply = new PurchaseApply();
            //数据状态: 1:正常
            purchaseApply.setDataState("1");
            //采购状态: 0:已录入
            purchaseApply.setCheckState("0");
            //采购状态: 2:已上报
            purchaseApply.setReportState("2");
            //公司编码
            String compCode = "";
            if(!UserUtils.isSysAdmin()){
                //公司管理员
                if(UserUtils.isCompAdmin()){
                    compCode = UserUtils.getCurrentUser().getCompany().getCompCode();
                }else{
                    //创建用户
                    purchaseApply.setCreateBy(user.getUsId());
                }
            }
            Page<PurchaseApply> pages = purchaseApplyService.selectPage(page, purchaseApply,compCode);
            json.put("total", pages.getTotal());
            json.put("rows", getJSONArray(jsonArray, pages, user));
            ResManager.getTextOut(response).print(json);
            logger.info("已录入事项->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("已录入事项->Exception " + e.getMessage());
        }
    }




    /**
     * 审核中事项
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:workflow_purchase_myAuditPage")
    @RequestMapping(value = "/myAuditList.do", method = RequestMethod.POST)
    public void myAuditList(HttpServletResponse response, PurchaseApplyIn in) {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        try {
            logger.info("审核中事项->>开始");
            User user = UserUtils.getCurrentUser();
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //审核中请购单<<参与流程审核用户可看>>
            PurchaseApply purchaseApply = new PurchaseApply();
            //数据状态: 1:正常
            purchaseApply.setDataState("1");
            //采购状态: 1:审核中
            purchaseApply.setCheckState("1");
            //采购状态: 2:已上报
            purchaseApply.setReportState("2");
            //公司编码
            String compCode = "";
            if(!UserUtils.isSysAdmin()){
                //公司管理员
                if(UserUtils.isCompAdmin()){
                    compCode = UserUtils.getCurrentUser().getCompany().getCompCode();
                }else{
                    //系统用户
                    purchaseApply.setUser(UserUtils.getCurrentUser());
                }
            }
            Page<PurchaseApply> pages = purchaseApplyService.queryPage(page, purchaseApply,compCode);
            json.put("total", pages.getTotal());
            json.put("rows", getJSONArray(jsonArray, pages, user));
            ResManager.getTextOut(response).print(json);
            logger.info("审核中事项->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("审核中事项->Exception " + e.getMessage());
        }
    }



    /**
     * 已通过事项
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:workflow_purchase_myFinishPage")
    @RequestMapping(value = "/myFinishList.do", method = RequestMethod.POST)
    public void myFinishList(HttpServletResponse response, PurchaseApplyIn in) {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        try {
            logger.info("已通过事项->>开始");
            User user = UserUtils.getCurrentUser();
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //已通过请购单<<参与流程审核用户可看>>
            PurchaseApply purchaseApply = new PurchaseApply();
            //数据状态: 1:正常
            purchaseApply.setDataState("1");
            //采购状态: 2:已通过
            purchaseApply.setCheckState("2");
            //上报状态  2:已上报
            purchaseApply.setReportState("2");
            //公司编码
            String compCode = "";
            if(!UserUtils.isSysAdmin()){
                //公司管理员
                if(UserUtils.isCompAdmin()){
                    compCode = UserUtils.getCurrentUser().getCompany().getCompCode();
                }else{
                    //系统用户
                    purchaseApply.setUser(UserUtils.getCurrentUser());
                }
            }
            Page<PurchaseApply> pages = purchaseApplyService.queryPage(page, purchaseApply,compCode);
            json.put("total", pages.getTotal());
            json.put("rows", getJSONArray(jsonArray, pages, user));
            ResManager.getTextOut(response).print(json);
            logger.info("已通过事项->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("已通过事项->Exception " + e.getMessage());
        }
    }



    /**
     * 已驳回事项
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:workflow_purchase_myReturnPage")
    @RequestMapping(value = "/myReturnList.do", method = RequestMethod.POST)
    public void myReturnList(HttpServletResponse response, PurchaseApplyIn in) {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        try {
            logger.info("已驳回事项->>开始");
            User user = UserUtils.getCurrentUser();
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //已驳回请购单<<参与流程审核用户可看>>
            PurchaseApply purchaseApply = new PurchaseApply();
            //数据状态 1:正常
            purchaseApply.setDataState("1");
            //采购状态 3:已驳回
            purchaseApply.setCheckState("3");
            //公司编码
            String compCode = "";
            if(!UserUtils.isSysAdmin()){
                //公司管理员
                if(UserUtils.isCompAdmin()){
                    compCode = UserUtils.getCurrentUser().getCompany().getCompCode();
                }else{
                    //系统用户
                    purchaseApply.setUser(UserUtils.getCurrentUser());
                }
            }
            Page<PurchaseApply> pages = purchaseApplyService.queryPage(page, purchaseApply,compCode);
            json.put("total", pages.getTotal());
            json.put("rows", getJSONArray(jsonArray, pages, user));
            ResManager.getTextOut(response).print(json);
            logger.info("已驳回事项->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("已驳回事项->Exception " + e.getMessage());
        }
    }



    /**
     * 返回jsonArray
     * @param jsonArray
     * @param pages
     * @param user
     * @return
     */
    private JSONArray getJSONArray(JSONArray jsonArray, Page<PurchaseApply> pages, User user){
        try {
            if(pages.getRecords().size() > 0){
                for(PurchaseApply purchaseApply : pages.getRecords()){
                    JSONObject object = new JSONObject(purchaseApply);
                    object.put("prName", purchaseApply.getProject().getPrName());
                    object.put("coId", purchaseApply.getContract().getCoId());
                    object.put("coName", purchaseApply.getContract().getCoName());
                    object.put("coCode", purchaseApply.getContract().getCoCode());
                    object.put("coNumber", purchaseApply.getContract().getCoNumber());
                    object.put("purDate", DateTool.format(purchaseApply.getPurDate(), "yyyy-MM-dd HH:mm:ss"));
                    object.put("createDate", DateTool.format(purchaseApply.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                    object.put("updateDate", DateTool.format(purchaseApply.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
                    object.put("createPerson", user.getLoginName());
                    jsonArray.put(object);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
            return  jsonArray;
    }



    /**
     * 查看
     * @return
     */
    @RequiresPermissions("rules:workflow_purchase_myFinishView")
    @RequestMapping(value = "/toView.do", method = RequestMethod.GET)
    public String toView(PurchaseIn in, HttpServletRequest request) {
        try {
            logger.info("跳转至查看采购->>toView->>开始");
            //1. 获取采购对象
            PurchaseApply purchaseApply = iPurchaseApplyService.getPurchaseApplyByPurId(in.getPurId());

            //2. 获取采购详情
            EntityWrapper<PurchaseDetail> ewPurchaseDetail = new EntityWrapper<>();
            ewPurchaseDetail.eq("purd.purId", in.getPurId());
            List<PurchaseDetail> purchaseDetails = iPurchaseDetailService.getPurchaseDetails(ewPurchaseDetail);

            //3. 采购附件
            List<CommonFile> commonFiles = new ArrayList<>();
            EntityWrapper<PurchaseFile> ewPurchaseFile = new EntityWrapper<>();
            ewPurchaseFile.eq("purId", in.getPurId());
            List<PurchaseFile> purchaseFiles = iPurchaseFileService.selectList(ewPurchaseFile);
            if(null != purchaseFiles && purchaseFiles.size() > 0){
                List<String> fileIds = new ArrayList<>();
                for(PurchaseFile purchaseFile : purchaseFiles){
                    fileIds.add(purchaseFile.getFileId());
                }
                commonFiles = iCommonFileService.selectBatchIds(fileIds);
            }


            //4. 根据业务编号查询历史流程实例, 获取所有活动节点历史表（条件： 流程实例编号）
            String key = purchaseApply.getClass().getSimpleName();
            String businessKey = key + "." + in.getPurId();
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
            List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(historicProcessInstance.getId()).orderByHistoricActivityInstanceStartTime().asc().list();


            //5. 根据流程实例获取批注信息
            String processInstanceId = historicProcessInstance.getId();
            List<Comment> comments = taskService.getProcessInstanceComments(processInstanceId);

            //6. 根据流程实例编号查询历史任务表
            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).orderByHistoricTaskInstanceEndTime().desc().listPage(0, 6);
            Integer compId = UserUtils.getCurrentUser().getCompanyId();
            Map<String, String> empNames = iEmployeeService.getEmpNamesByCompId(String.valueOf(compId));

            //集合排序
            historicTaskInstances =  sortHistoricTaskInstanceList(historicTaskInstances);

            request.setAttribute("comments", comments);
            request.setAttribute("historicActivityInstances", historicActivityInstances);
            request.setAttribute("historicTaskInstances", historicTaskInstances);
            request.setAttribute("purchaseApply", purchaseApply);
            request.setAttribute("purchaseDetails", purchaseDetails);
            request.setAttribute("commonFiles", commonFiles);
            request.setAttribute("emNameMap", empNames);
            logger.info("跳转至查看采购->>toView->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("跳转至查看采购->>toView->>Exception " + e.getMessage());
        }
            return "workflow/purchase/view";
    }


    /**
     * 集合排序
     * @param historicTaskInstances
     * @return
     */
    public static List<HistoricTaskInstance> sortHistoricTaskInstanceList(List<HistoricTaskInstance> historicTaskInstances){
        Collections.sort(historicTaskInstances, new Comparator<HistoricTaskInstance>() {
            @Override
            public int compare(HistoricTaskInstance o1, HistoricTaskInstance o2) {
                if(Integer.parseInt(o1.getId()) > Integer.parseInt(o2.getId())){
                    return 1;
                }
                return -1;
            }
        });
                return historicTaskInstances;
    }



    /**
     * 删除采购申请
     * @param in
     * @param response
     */
    @RequiresPermissions("rules:workflow_purchase_myInputDel")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(PurchaseIn in, HttpServletResponse response){
        CommonResult result = new CommonResult();
        try {
            logger.info("删除采购申请->>开始");
            iPurchaseApplyService.delPurchaseByPurId(in.getPurId());
            result.setCode(Constants.CODE_SUCCESS);
            result.setMessage(Constants.ZHGD_WORKFLOW_BUSINESS_DEL_SUCCESS);
            logger.info("删除采购申请->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.CODE_FAIL);
            result.setMessage(Constants.ZHGD_WORKFLOW_BUSINESS_DEL_FAIL);
            logger.error("删除采购申请->>Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(result));
    }



    /**
     * 启动流程实例（申请请购）
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:workflow_purchase_myInputAdd")
    @RequestMapping(value = "/startProcess.do", method = RequestMethod.POST)
    public void startProcess(HttpServletResponse response, PurchaseIn in) {
        CommonResult commonResult = new CommonResult();
        try {
            logger.info("启动流程实例（申请请购）->>开始");
            User user = UserUtils.getCurrentUser();
            //1. 根据请购编号, 获取请购对象
            PurchaseApply purchaseApply = iPurchaseApplyService.selectById(in.getPurId());
            //2. 更新请购状态1（0:初始录入-->>1:审核中）
            purchaseApply.setCheckState("1");
            iPurchaseApplyService.updateById(purchaseApply);
            //3. 设置流程变量, 当前办理人
            Map<String, Object> variables = new HashMap<>();
            variables.put("departmentPerson", user.getLoginName());
            //4. 构建businessKey来启动流程实例
            String key = purchaseApply.getClass().getSimpleName();
            String businessKey = key + "." + in.getPurId();
            variables.put("businessKey",  businessKey);
            //5. 使用流程定义的key，启动流程实例，同时设置流程变量，同时向正在执行的执行对象表中的字段BUSINESS_KEY添加业务数据，同时让流程关联业务
            runtimeService.startProcessInstanceByKey(key, businessKey, variables);
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage("申请请购成功");
            logger.info("启动流程实例（申请请购）->>结束");
        } catch (Exception e){
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage("申请请购失败");
            e.printStackTrace();
            logger.error("启动流程实例（申请请购）->Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
    }

}
